package com.gandong8.derby.core.interceptor;

import com.gandong8.derby.core.exception.LoginRedirectException;
import com.gandong8.derby.core.util.RequestUtil;
import com.gandong8.derby.core.annoation.NotLogin;
import com.gandong8.derby.core.constant.DOConstant;
import com.gandong8.derby.core.exception.LoginException;
import com.gandong8.derby.pojo.entry.manual.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


@Slf4j
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if(!(o instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)o;
        Method method=handlerMethod.getMethod();
        if (method.isAnnotationPresent(NotLogin.class)) {
            NotLogin notLogin = method.getAnnotation(NotLogin.class);
            if (notLogin.pass()) {
                return true;
            }
        }
        User user = (User) RequestUtil.getSession(DOConstant.USER_SESSION);
        if(user == null) {
            if(StringUtils.isEmpty(RequestUtil.getHeader("ajax"))) {
                throw new LoginRedirectException("please login first");
            }
            throw new LoginException("please login first");
        }
        return true;
    }

}
